package code.Frame.userFrame;

import code.MYSQL;
import code.Main;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class orderFrame {
    public JPanel panel;
    private JTable order_list;
    private JLabel total_price;
    private JButton ok;
    private JButton del;
    private JButton add;
    private JTable dish_list;
    private JComboBox<String> shop_sel;
    private JComboBox<String> addr_sel;
    private int[] aid;
    private int[] sid;
    private int sid_now = -1;
    private float[] price;
    private String[] name; // 菜名
    private float tot;

    public boolean end = false;
    private int[] did;

    private class data
    {
        int did;
        int sid;
        String name;
        float price;
        int num;

        data(int sid, int did, String name, float price, int num)
        {
            this.sid = sid;
            this.did = did;
            this.name = name;
            this.price = price;
            this.num = num;
        }

        @Override
        public String toString()
        {
            return name + " " + String.format("%.2f", price) + "*" + num + " " + String.format("%.2f", price*num);
        }
    }

    private class order_to_shop
    {
        int sid;
        String description;
        float tot_price;

        order_to_shop(int sid)
        {
            this.sid = sid;
            tot_price = 0;
            description = "";
        }

        void add(data Data)
        {
            description = description + Data.toString() + "\n";
            tot_price += Data.price * Data.num;
        }
    }

    List<data> orders = new LinkedList<>();

    public orderFrame()
    {
        tot = 0;
        total_price.setText(String.valueOf(tot));
        set_shop();
        set_addr();
        set_order_list();
        set_dish_list();

        shop_sel.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (shop_sel.getSelectedIndex() > 0)
                {
                    refresh_dish_list(shop_sel.getSelectedIndex() - 1);
                    sid_now = sid[shop_sel.getSelectedIndex() - 1];
                }
            }
        });
        add.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                int dish_sel = dish_list.getSelectedRow();
                if (dish_sel == -1)
                    return;
                int num = (int) dish_list.getCellEditor(dish_sel, 2).getCellEditorValue();
                if (num == 0)
                    return;
                orders.add(new data(sid_now, did[dish_sel], name[dish_sel], price[dish_sel], num));
                tot += num * price[dish_sel];
                total_price.setText(String.format("%.2f", tot));
                update_order_list();
            }
        });
        del.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                int idx = order_list.getSelectedRow();
                if (idx == -1)
                    return;
                data old = orders.get(idx);
                tot -= old.num * old.price;
                total_price.setText(String.format("%.2f", tot));
                orders.remove(idx);
                update_order_list();
            }
        });
        ok.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (addr_sel.getSelectedIndex() == 0)
                {
                    JOptionPane.showMessageDialog(panel.getParent(), "请选择外送地址", "下单失败", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                HashMap<Integer, order_to_shop> result = new HashMap<>();
                for (data Data : orders)
                {
                    if (result.containsKey(Data.sid))
                        result.get(Data.sid).add(Data);
                    else
                    {
                        order_to_shop temp = new order_to_shop(Data.sid);
                        temp.add(Data);
                        result.put(Data.sid, temp);
                    }
                    try
                    {
                        MYSQL.maintain("update dish set sale = sale + " + Data.num + "\n" +
                                "where DID = " + Data.did
                        );
                    } catch (SQLException ex)
                    {
                        throw new RuntimeException(ex);
                    }
                }
                result.forEach((id, value)->{
                    try
                    {
                        MYSQL.maintain("insert into orders(AID, UID, SID, price, description) \n" +
                                "values(" + aid[addr_sel.getSelectedIndex()-1] + ", " + // AID
                                (Main.uid - 100000000) + ", " +                         // UID
                                value.sid + ", " +                                      // SID
                                String.format("%.2f", value.tot_price) + ", " +         // price
                                "'" + value.description + "'" + ")"                     // description
                        );
                    } catch (SQLException ex)
                    {
                        throw new RuntimeException(ex);
                    }
                });
                JOptionPane.showMessageDialog(panel.getParent(), "下单成功");
                end = true;
            }
        });
    }

    private void set_addr()
    {
        String[][] res;
        try
        {
            res = MYSQL.query_user_addr(Main.uid - 100000000);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        addr_sel.addItem("");
        aid = new int[res.length];
        for (int i=0;i<res.length;i++)
        {
            aid[i] = Integer.parseInt(res[i][1]);
            addr_sel.addItem(res[i][0]);
        }
    }

    private void refresh_dish_list(int idx)
    {
        try
        {
            String[][] temp = MYSQL.query_shop_dish(sid[idx]);
            update_dish_list(temp);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void set_shop()
    {
        shop_sel.addItem("");
        try
        {
            String[][] temp = MYSQL.getAllshop();
            sid = new int[temp.length];
            int i = 0;
            for (String[] t: temp)
            {
                sid[i++] = Integer.parseInt(t[0]);
                shop_sel.addItem(t[1]);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void set_order_list()
    {
        String[] colNames = {"菜名", "单价", "数量", "总价"};
        DefaultTableModel model = new DefaultTableModel(null, colNames);
        order_list.setModel(model);
    }

    private void update_order_list()
    {
        String[] colNames = {"菜名", "单价", "数量", "总价"};
        String[][] Data = new String[orders.size()][4];
        int i = 0;
        for (data d : orders)
        {
            Data[i][0] = d.name;
            Data[i][1] = String.format("%.2f", d.price);
            Data[i][2] = String.valueOf(d.num);
            Data[i++][3] = String.format("%.2f", d.num * d.price);
        }
        DefaultTableModel model = new DefaultTableModel(Data, colNames);
        order_list.setModel(model);
    }

    private void set_dish_list()
    {
        String[] colNames = {"菜名", "单价", "数量"};
        DefaultTableModel model = new DefaultTableModel(null, colNames);
        dish_list.setModel(model);
    }

    private void update_dish_list(String[][] temp)
    {
        if (temp.length == 0)
            return ;
        String[] colNames = {"菜名", "单价", "数量"};
        Object[][] Data = new Object[temp.length][3];
        name = new String[temp.length];
        price = new float[temp.length];
        did = new int[temp.length];
        int i = 0;
        for (String[] t : temp)
        {
            did[i] = Integer.parseInt(t[0]);
            name[i] = t[1];
            price[i] = Float.parseFloat(t[2]);
            Data[i][0] = t[1];
            Data[i][1] = t[2];
            Data[i++][2] = 0;
        }
        DefaultTableModel model = new DefaultTableModel(Data, colNames){
            @Override
            public boolean isCellEditable(int row, int column) {
                return column >= 2;
            }
        };
        dish_list.setModel(model);
        dish_list.getColumn("数量").setCellRenderer(new myRender());
        dish_list.getColumn("数量").setCellEditor(new myEditer());
    }
}
